//
//  HGScanCodeVC.m
//  RedWinMall
//
//  Created by HeDianZhao on 2018/8/12.
//  Copyright © 2018年 HeDianZhao. All rights reserved.
//

#import "HGScanCodeVC.h"
#import <AVFoundation/AVFoundation.h>
#import "XZScannView.h"

@interface HGScanCodeVC ()<AVCaptureMetadataOutputObjectsDelegate>

@property (strong, nonatomic) AVCaptureSession * captureSession;

@property (strong, nonatomic) AVCaptureVideoPreviewLayer * videoPreviewLayer;

@property (nonatomic, strong) XZScannView *scannView;

@end

@implementation HGScanCodeVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initSubViews];
}

- (void)initSubViews {
    [self loadScanView];
}

- (void)loadScanView {
    
    [AVCaptureDevice requestAccessForMediaType:AVMediaTypeVideo completionHandler:^(BOOL granted) {
        dispatch_async(dispatch_get_main_queue(), ^{
            
            if (!granted) {
                NSString *title = @"请在iPhone的”设置-隐私-相机“选项中，允许App访问你的相机";
                UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:title message:@"" delegate:nil cancelButtonTitle:@"好" otherButtonTitles:nil];
                [alertView show];
                return;
            }
            
            //配置扫描view
            self.captureSession = [[AVCaptureSession alloc] init];
            [self.captureSession beginConfiguration];
            
            AVCaptureDevice *device = [AVCaptureDevice defaultDeviceWithMediaType:(AVMediaTypeVideo)];
            
            NSError *error = nil;
            AVCaptureDeviceInput *catpureInput = [AVCaptureDeviceInput deviceInputWithDevice:device error:&error];
            if (error == nil) {
                if ([self.captureSession canAddInput:catpureInput]) {
                    [self.captureSession addInput:catpureInput];
                }
            } else {
                NSLog(@"error %@",error);
            }
            
            AVCaptureMetadataOutput *metadtaOutput = [[AVCaptureMetadataOutput alloc] init];
            [metadtaOutput setMetadataObjectsDelegate:self queue:dispatch_get_main_queue()];
            if ([self.captureSession canAddOutput:metadtaOutput]) {
                [self.captureSession addOutput:metadtaOutput];
                metadtaOutput.metadataObjectTypes = @[AVMetadataObjectTypeEAN13Code,AVMetadataObjectTypeQRCode];
            }
            
            CALayer *layer = [AVCaptureVideoPreviewLayer layerWithSession:self.captureSession];
            layer.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight);
            [self.view.layer addSublayer:layer];
            
            [self.captureSession commitConfiguration];
            
            [self.captureSession startRunning];
            
            self.scannView = [[XZScannView alloc] initWithFrame:self.view.bounds size:CGSizeMake(300, 500) offsetY:-15];
            self.scannView.backgroundColor = [UIColor clearColor];
            self.scannView.deflutColor = kColorWithFloat(0x00a0e9);
            self.scannView.autoresizingMask = UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight;
            [self.view addSubview:self.scannView];
            
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                [self.scannView startAnimation];
            });
        });
    }];
}

#pragma mark - AVCaptureMetadataOutputObjectsDelegate
- (void)captureOutput:(AVCaptureOutput *)output didOutputMetadataObjects:(NSArray<__kindof AVMetadataObject *> *)metadataObjects fromConnection:(AVCaptureConnection *)connection {
    NSString *str = nil;
    for (AVMetadataObject *object in metadataObjects) {
        str = [(AVMetadataMachineReadableCodeObject *)object stringValue];
        break;
    }
    if (str != nil) {
        NSLog(@"%@",str);
        [self.captureSession stopRunning];
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self.scannView stoptAnimation];
        });
    }
}

@end
